package com.fxsh168.server.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fxsh168.server.fragments.PersonFragment;
import com.fxsh168.server.R;
import com.fxsh168.server.base.CheckPermissionsActivity;
import com.fxsh168.server.interfaces.Constant;
import com.fxsh168.server.entitys.PersonInfoEntity;
import com.fxsh168.server.entitys.RegiYZMCG;
import com.fxsh168.server.otherviews.SelectPicPopupWindow;
import com.fxsh168.server.otherviews.WheelView;
import com.fxsh168.server.utils.CircleImageView;
import com.fxsh168.server.utils.GetLastZF;
import com.fxsh168.server.utils.GetPhotoImgPath;
import com.fxsh168.server.utils.ImgDealUtils;
import com.fxsh168.server.utils.MD5Utils;
import com.fxsh168.server.utils.RegExp;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class MyInfoActivity extends CheckPermissionsActivity {
    private PersonInfoEntity.DataBean data;
    private EditText mGetNickName, mGetAge;
    /* 头像文件 */
    private static String IMAGE_FILE_NAME = System.currentTimeMillis() + ".jpg";
    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    // 裁剪后图片的宽(X)和高(Y),36 X 36的正方形。
    private static int sex = 0;
    private CircleImageView headImage;

    //自定义的弹出框类
    private Bitmap mPhoto;
    private String mPassword, photoPath;
    File mFile, tempFile;
    private String token, mNewPhone, mPhotoName;
    String mFileNamePath = "/sdcard/myImage/" + "myPortrait" + ".jpg";
    TextView teSex;
    //自定义的弹出框类
    SelectPicPopupWindow menuWindow;
    LinearLayout mChooseSex;
    List<String> listNumber;
    PopupWindows_man popupWindows_nummber;
    WheelView peopleWheel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_information);
        SharedPreferences sp = getSharedPreferences(Constant.LOGINCLASS, MODE_PRIVATE);
        mNewPhone = sp.getString("mPhone", "");
        token = sp.getString("token", "");
        mPassword = sp.getString("mPassword", "");

        mChooseSex = (LinearLayout) findViewById(R.id.mChooseSex);
        teSex = (TextView) findViewById(R.id.teSex);
        mGetNickName = (EditText) findViewById(R.id.getName);
        mGetAge = (EditText) findViewById(R.id.getAge);
        headImage = (CircleImageView) findViewById(R.id.portrat);
        mChooseSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindows_nummber = new PopupWindows_man(MyInfoActivity.this, view);
            }
        });
        initScan();
    }

    //            性别选择
    public class PopupWindows_man extends PopupWindow {
        View view;
        String nummbrtMan;

        PopupWindows_man(Context mContext, View parent) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.peoplenumndialog_layout, null);
            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.CENTER, 0, 0);
            update();
            listNumber = new ArrayList<>();
            listNumber.add(0, "男");
            listNumber.add(1, "女");
            peopleWheel = (WheelView) view.findViewById(R.id.peopleWheel);
            TextView teok = (TextView) view.findViewById(R.id.te_ok);
            TextView tecancel = (TextView) view.findViewById(R.id.te_cancel);
            peopleWheel.setOffset(0);
            peopleWheel.setSeletion(1);
            peopleWheel.setItems(listNumber);
            peopleWheel.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
                @Override
                public void onSelected(int selectedIndex, String item) {
                    nummbrtMan = item;
                    Log.e("tag", "性别选择" + selectedIndex + "···" + item);
                }
            });
            //   点击事件
            teok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    teSex.setText(nummbrtMan);
                    if (nummbrtMan.equals("男")) {
                        sex = 1;
                    } else {
                        sex = 0;
                    }
                    popupWindows_nummber.dismiss();
                }
            });
            tecancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindows_nummber.dismiss();
                }
            });
        }
    }


    //个人中心资料查看
    public void initScan() {
        OkHttpUtils.post().addParams("phone", mNewPhone).addParams("token", token)
                .url(Constant.GETPERSONINFOPATH).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast("连接不上服务器!");
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("tag", "response=" + response);
                if (response != null) {
                    PersonInfoEntity personInfoEntity = new Gson().fromJson(response, PersonInfoEntity.class);
                    if (personInfoEntity != null) {
                        String code = personInfoEntity.getCode().trim();
                        if (code.equals(200 + "")) {
                            data = personInfoEntity.getData();
                            //头像路径
                            photoPath = data.getPhoto().toString().trim();
                            Message message = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("photoPath", photoPath);
                            message.setData(bundle);
                            handler.sendMessage(message);
                            String nickName = data.getUsername().toString().trim();//昵称
                            String sexmyinf = data.getSex().toString().trim();//性别
                            String agemyinf = data.getAge().toString().trim();//年龄
                            if (!TextUtils.isEmpty(nickName)) {
                                //设置昵称
                                mGetNickName.setText(nickName);
                            } else {
                                mGetNickName.setText("");
                            }
                            //设置性别
                            if (!TextUtils.isEmpty(sexmyinf)) {
                                Integer sex3 = Integer.valueOf(sexmyinf);
                                sex = sex3;
                                switch (sex) {//设置男女
                                    case 1:
                                        teSex.setText("男");
                                        break;
                                    case 0:
                                        teSex.setText("女");
                                        break;
                                    default:
                                        break;
                                }
                            }
                            //设置年龄
                            if (!TextUtils.isEmpty(agemyinf)) {
                                mGetAge.setText(agemyinf);
                            } else {
                                mGetAge.setText("0");
                            }
                        }
                    }
                }
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String czlphotoPath = bundle.getString("photoPath");
            //用Glide加载头像图片
            if (!TextUtils.isEmpty(czlphotoPath)) {
                Glide.with(MyInfoActivity.this).load(czlphotoPath).centerCrop().crossFade().into(headImage);
                //将下载的图片保存和上传的图片名字和路径一样，方便上传
                headImage.setDrawingCacheEnabled(true);
                Bitmap drawingCache = headImage.getDrawingCache();
                //把裁剪后的图片保存起来
                FileOutputStream b = null;
                mFile = new File("/sdcard/myImage/");
                if (!mFile.exists()) {
                    mFile.mkdirs();// 创建文件夹
                }

                //文件路径
                mFileNamePath = "/sdcard/myImage/" + "myPortrait" + ".jpg";
                //文件名
                mPhotoName = GetLastZF.getLatZF(mFileNamePath, "/");
                try {
                    b = new FileOutputStream(mFileNamePath);
                    drawingCache.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        b.flush();
                        b.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                headImage.setDrawingCacheEnabled(false);
            } else {
                headImage.setImageResource(R.mipmap.waiting_head);//图片为空头像设置为默认图片
                headImage.setFocusable(true);
            }
        }
    };

    //  手机号修改
    public void btnBinPhone(View view) {
        startActivity(new Intent(this, ChangePhone.class));
    }

    //保存资料
    public void btnSave(View view) {
        //密码加密
        String jMPassword = MD5Utils.MD532(mPassword);
        //token生成规则
        //md5(lis+账号+bin+密码+www625kejicom)
        //参数:token 手机号phone 姓名username 年龄age 性别(1为女0为男)sex(0,1) 头像photo
        String token = MD5Utils.MD532("lis" + mNewPhone + "bin" + jMPassword + "www625kejicom");
        final String nickname = mGetNickName.getText().toString().trim();
        String age = mGetAge.getText().toString().trim();
        //获得头像文件
        File photoFile = new File(mFileNamePath);
        Log.e("tag", "图片上传:" + photoFile);
        //获得文件名称
        String fileName = mPhotoName;
        if (mPhoto != null) {
            if (!TextUtils.isEmpty(nickname)) {
                if (RegExp.checkAge(age)) {
                    OkHttpUtils.post().addParams("token", token).addParams("phone", mNewPhone)
                            .addParams("username", nickname).addParams("age", age).addParams("sex", sex + "")
                            .addFile("photo", fileName, photoFile).url(Constant.XIUGAIZILIAO)
                            .build().execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            showToast("连接不上服务器!");
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            RegiYZMCG regiYZMCG = new Gson().fromJson(response, RegiYZMCG.class);
                            String code = regiYZMCG.getCode().trim();
                            if (code.equals(200 + "")) {
                                showToast("修改成功!");
                                Intent intent = new Intent(MyInfoActivity.this, PersonFragment.class);
                                intent.putExtra("mFileNamePath", mFileNamePath);
                                intent.putExtra("nickname", nickname);
                                MyInfoActivity.this.setResult(Constant.MYINFORMATIONRETOPERSONSPONDCODE, intent);
                                MyInfoActivity.this.finish();
                                Bitmap bitmap = BitmapFactory.decodeFile(mFileNamePath);
                                headImage.setImageBitmap(bitmap);
                            } else if (code.equals(202 + "")) {
                                showToast("修改失败!");
                            }
                        }
                    });
                } else {
                    mGetAge.setError("请填写正确的年龄!");
                }
            } else {
                mGetNickName.setError("昵称不能为空!");
            }
        } else {
            showToast("头像为空,请选择头像!");
        }

    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            showToast("权限申请成功");
        } else {
            showToast("请前往设置中心打开相机，相册权限");
        }
    }

    //       修改头像
    public void btnPortrat(View view) {
        //实例化SelectPicPopupWindow
        menuWindow = new SelectPicPopupWindow(MyInfoActivity.this, itemsOnClick);
        //显示窗口
        menuWindow.showAtLocation(MyInfoActivity.this.findViewById(R.id.myInformation), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
    }

    //    权限
    protected String[] needContactsPermissions = {
            Manifest.permission.CAMERA};

    private void requestPermission() {
        if (!mayRequestPermission(needContactsPermissions)) {
            return;
        }
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.buttonLocal:
                    requestPermission();
                    choseHeadImageFromGallery();
                    break;
                case R.id.buttonCamera:
                    requestPermission();
                    choseHeadImageFromCameraCapture();
                    break;
                default:
                    break;
            }
        }
    };

    // 从本地相册选取图片作为头像
    private void choseHeadImageFromGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image//*");
        startActivityForResult(intent, CODE_GALLERY_REQUEST);
    }

    // 启动手机相机拍摄照片作为头像
    private void choseHeadImageFromCameraCapture() {
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可用，存储照片文件
        if (hasSdcard()) {
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
                    .getExternalStorageDirectory(), IMAGE_FILE_NAME)));
        }
        startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case RESULT_OK:
                Log.e("TAG", "ActivityResult resultCode error");//此处的 RESULT_OK 是系统自定义得一个常量
                break;
            // 用户没有进行有效的设置操作，返回
            case RESULT_CANCELED:
                Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
                break;
            case CODE_GALLERY_REQUEST:
                if (intent != null && !TextUtils.isEmpty(intent.toString().trim())) {
                    Uri uri = intent.getData();
                    if (uri != null && !TextUtils.isEmpty(uri.toString().trim())) {
                        String Selpath = GetPhotoImgPath.getPath(intent, MyInfoActivity.this, MyInfoActivity.this);
                        if (!TextUtils.isEmpty(Selpath)) {
                            getImg(Selpath);
                        }
                    }
                }
                break;
            case CODE_CAMERA_REQUEST:
                if (hasSdcard()) {
                    tempFile = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
                    if (tempFile != null) {
                        String cameraPath = tempFile.getAbsolutePath().trim();
                        if (!TextUtils.isEmpty(cameraPath) && (cameraPath != null)) {
                            getImg(cameraPath);
                        }
                    }
                } else {
                    Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG).show();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, intent);
    }


    private Bitmap getImg(String mSelectPath) {
        if (mSelectPath != null && (!TextUtils.isEmpty(mSelectPath))) {
            Log.e("mSelectPath", "mSelectPath=" + mSelectPath);
            mPhoto = ImgDealUtils.reSizeBitmap(mSelectPath, 800f, 480f);
            ByteArrayOutputStream baos22 = new ByteArrayOutputStream();
            if (mPhoto != null) {
                mPhoto.compress(Bitmap.CompressFormat.JPEG, 100, baos22);
                FileOutputStream fos = null;
                mFile = new File("/sdcard/myImage/");
                if (!mFile.exists()) {
                    mFile.mkdirs();// 创建文件夹
                }
                //文件路径
                mFileNamePath = "/sdcard/myImage/" + "myPortrait" + ".png";
                //获取最后文件名
                mPhotoName = GetLastZF.getLatZF(mFileNamePath, "/");
                try {
                    fos = new FileOutputStream(mFileNamePath);
                    if (mPhoto != null) {
                        mPhoto.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        headImage.setImageBitmap(mPhoto);
                        return mPhoto;
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
